# -*- Mode: Python -*- vi:si:et:sw=4:sts=4:ts=4:syntax=python
import os
from cerbero.utils import needs_xcode8_sdk_workaround

class Recipe(recipe.Recipe):
    name = 'fontconfig'
    version = '2.12.6'
    stype = SourceType.TARBALL
    url = 'https://www.freedesktop.org/software/fontconfig/release/fontconfig-%(version)s.tar.gz'
    tarball_checksum = '064b9ebf060c9e77011733ac9dc0e2ce92870b574cca2405e11f5353a683c334'
    licenses = [{License.MIT: ['COPYING']}]
    configure_options = '--disable-docs'
    deps = ['expat', 'freetype', 'zlib', 'bzip2']
    patches = [
        'fontconfig/0001-Fix-cross-compilation-by-passing-CPPFLAGS-to-CPP.patch',
        # https://gitlab.freedesktop.org/fontconfig/fontconfig/-/merge_requests/88
        'fontconfig/0002-fcatomic-Fix-EXC_BAD_ACCESS-on-iOS-ARM64.patch',
        'fontconfig/0003-Completely-disable-building-of-tests.patch',
    ]

    files_libs = ['libfontconfig']
    files_etc = [
        'etc/fonts/conf.d',
        'etc/fonts/fonts.conf',
        'share/fontconfig'
        ]
    files_devel = ['lib/pkgconfig/fontconfig.pc', 'include/fontconfig']


    def prepare(self):
        if self.config.target_platform in (Platform.WINDOWS, Platform.ANDROID):
            self.deps.append('libiconv')
        if needs_xcode8_sdk_workaround(self.config):
            self.set_env('ac_cv_func_mkostemp', 'no')

        if self.config.target_platform == Platform.WINDOWS:
            if self.config.target_arch == Architecture.X86_64:
                self.configure_options += ' --with-arch=x86_64 '
            else:
                self.configure_options += ' --with-arch=i686 '
        else:
            self.autoreconf = True
            self.patches += ['fontconfig/0003-configure-Allow-static-build.patch']

    def post_install(self):
        # Create relative symlinks to prevent breakage during packaging
        if self.config.platform != Platform.WINDOWS:
            confddir = os.path.join(self.config.prefix, 'etc', 'fonts', 'conf.d')
            linksrc = os.path.join('..', '..', '..', 'share', 'fontconfig', 'conf.avail')
            for f in os.listdir(confddir):
                if not f.endswith('.conf'):
                    continue
                os.remove(os.path.join(confddir, f))
                os.symlink(os.path.join(linksrc, f), os.path.join(confddir, f))
        super().post_install()
